<template>
  <div id="systemUser">
    <!-- <h1 class="title">系统用户管理</h1> -->
    <div class="content">
      <div class="tableWrap" v-if="data.editFlag">
        <HETTable1
          ref="systemUserTable"
          :tableData="data.tableData"
          :tHead="data.tHead"
          :total="data.total"
          :size="10"
          :headerOperation="data.headerOperation"
          @getTableData="initTable"
        >
          <template #name>
            <el-table-column label="用户名">
              <template #default="scope">
                {{ scope.row.username }}&nbsp;&nbsp;<span v-show="scope.row.locked"
                  ><el-icon><Lock /></el-icon
                ></span>
              </template>
            </el-table-column>
          </template>
          <template #locked>
            <el-table-column label="是否锁定">
              <template #default="scope">
                <el-switch v-model="scope.row.locked" :active-value="1" :inactive-value="0" :disabled="scope.row.role == '默认管理员'" @change="setLocked(scope.row)"></el-switch>
              </template>
            </el-table-column>
          </template>
          <template #operation>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button text type="primary" @click="edit(scope.row)" :disabled="scope.row.role == '默认管理员'">编辑</el-button>
                <el-button text type="primary" @click="del(scope.row)" :disabled="scope.row.role == '默认管理员'||scope.row.locked">删除</el-button>

              </template>
            </el-table-column>
          </template>
        </HETTable1>
      </div>
      <div class="editWrap" v-else>
        <div class="item-card setting-box">
          <h6>个性资料</h6>
          <el-form
            ref="ruleFormRef"
            :model="data.ruleForm"
            status-icon
            :rules="data.rules"
            label-width="120px"
            class="elform ml-10"
          >
            <el-form-item label="用户状态：" prop="locked">
              <el-switch
                v-model="data.ruleForm.locked"
                size="large"
                inline-prompt
                :active-value="1"
                :inactive-value="0"
                active-text="锁定"
                inactive-text="解锁"
              />
            </el-form-item>
            <el-form-item label="用户名：" prop="username">
              <el-input v-model="data.ruleForm.username" autocomplete="off" />
            </el-form-item>
            <!--            <el-form-item label="姓名：" prop="stuffName">-->
            <!--              <el-input v-model="data.ruleForm.stuffName" autocomplete="off" />-->
            <!--            </el-form-item>-->
          </el-form>
        </div>
        <div class="item-card setting-box">
          <h6>用户密码</h6>
          <el-form
            ref="ruleFormRef"
            :model="data.ruleForm"
            status-icon
            :rules="data.rules"
            label-width="120px"
            class="elform ml-10"
          >
            <el-form-item label="新密码：" prop="password">
              <el-input
                v-model="data.ruleForm.password"
                type="password"
                autocomplete="off"
                show-password
              />
            </el-form-item>
            <el-form-item label="确认密码：" prop="checkPass">
              <el-input
                v-model="data.ruleForm.checkPass"
                type="password"
                autocomplete="off"
                show-password
              />
            </el-form-item>
          </el-form>
        </div>
        <div class="item-card setting-box">
          <h6>角色</h6>
          <el-form-item class="ml-16">
            <el-radio-group v-model="data.ruleForm.role">
              <el-radio label="默认管理员" disabled/>
              <el-radio label="管理员" />
              <el-radio label="审计员" />
              <el-radio label="操作员" />
            </el-radio-group>
          </el-form-item>
        </div>
        <div class="btns">
          <el-button :icon="Close" @click="data.editFlag = true"
            >取消</el-button
          >
          <el-button
            :icon="Check"
            @click="submitForm(ruleFormRef)"
            type="primary"
            >确定
          </el-button>
        </div>
      </div>

      <addSystemUser
        :dialogAsync="addUserDialog"
        :name="guardUsername"
        @addTerminalUser="handleAddTerminalUser"
        @setPassword="handleSetPassword"
        @closeDialog="addUserDialog = false"
      ></addSystemUser>
    </div>
  </div>
</template>

<script setup>
import { validPassword } from "~/utils/common/validation.js";
import { ref, reactive, onMounted, computed, markRaw, nextTick } from "vue";
import {
  req_getSystemUsers,
  req_setSystemUsers,
  req_lockedSystemUser,
  req_unlockSystemUser,
  req_addSystemUser,
  req_DelSystemUsers,
} from "~/utils/axios/index.js";
import {
  Lock,
  Close,
  Check,
  DocumentCopy,
  Upload,
  Plus,
} from "@element-plus/icons-vue";
import addSystemUser from "./components/addSystemUser.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import moment from "moment";

const addUserDialog = ref(false);
const ruleFormRef = ref();
const systemUserTable = ref();
const dialogAsync = ref(false);
const validatePass = (rule, value, callback) => {
  if (data.ruleForm.checkPass !== "") {
    if (!ruleFormRef.value) return;
    ruleFormRef.value.validateField("checkPass", () => null);
  }
  callback();
};
const validatePass2 = (rule, value, callback) => {
  if (value !== data.ruleForm.password) {
    callback(new Error("两次输入的密码不一致！"));
  } else {
    callback();
  }
};
const validatePass3 = (rule, value, callback) => {
  if (value !== data.ruleAddForm.passwordHash) {
    callback(new Error("两次输入的密码不一致！"));
  } else {
    callback();
  }
};
const validName = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输入用户名"));
  } else if (value.length > 64) {
    callback(new Error("用户名不能超过64个字符"));
  } else {
    callback();
  }
};
const validStuffName = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输入姓名"));
  } else if (value.length > 64) {
    callback(new Error("姓名不能超过64个字符"));
  } else {
    callback();
  }
};

const ruleAddForm = {
  name: "",
  passwordHash: "",
  checkPass: "",
  role: "",
};
const data = reactive({
  tHead: [
    {
      label: "用户名",
      prop: "username",
      isCustom: true,
      slotName: "name",
    },
    {
      label: "角色",
      prop: "role",
      // isCustom: false,
      // slotName: "_roles",
    },
    {
      label: "是否锁定",
      prop: "locked",
      isCustom: true,
      slotName: "locked",
    },
    {
      label: "上次登录时间",
      prop: "lastLoginAt",
      // isCustom: false,
      // slotName: "lastLogin",
    },
    {
      label: "操作",
      prop: "operation",
      isCustom: true,
      slotName: "operation",
    },
  ],
  tableData: [],
  total: 0,
  headerOperation: [
    {
      name: "新增",
      icon: markRaw(Plus),
      handleClick: () => {
        addUserDialog.value = true;
      },
    },
  ],
  editFlag: true,
  addFlag: false,
  ruleForm: {},
  rules: {
    password: [
      { required: true, message: "请输入密码", trigger: "blur" },
      {
        validator: (rule, value, callback) => {
          // 自定义验证规则
          const regex =
            /^[A-Za-z0-9!@#\$%\^&\*()_+={}\[\]|\\:;"'<>,.?/~`-]{8,25}$/;
          if (!regex.test(value)) {
            callback(new Error("必须是字母、数字组合，长度在8到25位之间"));
          } else {
            callback();
          }
        },
        trigger: "blur",
      },
    ],
    checkPass: [{ validator: validatePass2, trigger: "blur" }],
    checkPass2: [{ validator: validatePass3, trigger: "blur" }],
    username: [
      { required: true, message: "请输入用户名", trigger: "blur" },
      { min: 3, max: 16, message: "长度在 3 到 16 个字符", trigger: "blur" },
    ],
    stuffName: [{ validator: validStuffName, trigger: "blur" }],
  },
});
const initTable = (params) => {
  systemUserTable.value.loading();
  req_getSystemUsers(params)
    .then((res) => {
      systemUserTable.value.finish();
      data.total = res.data.data.total
      data.tableData = res.data.data.rows
    })
    .catch((err) => {
      systemUserTable.value.finish();
    });
};

const setLocked = (row) => {
  req_setSystemUsers(row).then(res => {
    res.data.succeed?ElMessage.success('设置成功'):ElMessage.error("设置失败")
    systemUserTable.value.getTableData()
  })
}

const edit = (row) => {
  data.editFlag = false;
  data.ruleForm = { ...row, password: "", checkPass: "" };
};

const del = (row) => {
  ElMessageBox.confirm("确定要删除？", "删除用户", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    center: true,
    closeOnClickModal: false,
  }).then(() => {
    req_DelSystemUsers(row.id).then((res) => {
      if (res.data.succeed) {
        ElMessage({
          type: "success",
          message: "删除成功",
        });
      } else {
        ElMessage.error("删除失败");
      }
      initTable();
    });
  });
};

const submitForm = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      let param = {
        ...data.ruleForm,
      };
      req_setSystemUsers(param).then((res) => {
        if (res) {
          if (res.data.succeed) {
            ElMessage({
              type: "success",
              message: "修改成功",
            });
            data.editFlag = true;
            initTable();
          } else {
            ElMessage.error("修改失败")
          }
        }
      });
    } else {
      return false;
    }
  });
};

const handleAddTerminalUser = (data) => {
  delete data.oldPasswordHash;
  delete data.passwordConfirm;
  req_addSystemUser({ ...data }).then((res) => {
    res.data.succeed
      ? ElMessage.success("新建成功")
      : ElMessage.error("新建失败");
    addUserDialog.value = false;
    systemUserTable.value.getTableData();
  });
};

const adduser = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      if (ruleAddForm.passwordHash) {
        delete data.ruleForm.checkPass2;
      } else {
        delete data.ruleForm.passwordHash;
        delete data.ruleForm.checkPass2;
      }
      req_setSystemUsers(ruleAddForm).then((res) => {
        if (res) {
          ElMessage({
            type: "success",
            message: "修改成功",
          });
          data.editFlag = true;
          initTable();
        }
      });
    } else {
      return false;
    }
  });
};
</script>

<style lang="scss" scoped>
#systemUser {
  .back {
    display: flex;
    align-items: center;
    margin: 0 0 10px -10px;
  }

  .link {
    margin: 0 5px;
    color: #951297;
    cursor: pointer;
  }

  .edit-disabled,
  .del-btn {
    color: #c282c3;
    pointer-events: none;
    cursor: default;
  }

  .item-card {
    // background-color: #fff;
    border-radius: 8px;
    margin-bottom: 10px;
    padding: 0 15px 5px;

    h6 {
      font-size: 16px;
      // color: #333;
      padding: 15px 0;
    }

    :deep(.el-input) {
      width: 30%;
    }
  }

  .btns {
    display: flex;
  }
}
</style>
